package com.bbf.tio.server;

import com.bbf.tio.common.TioConstants;
import com.bbf.tio.common.TioPacket;
import org.tio.server.AioServer;
import org.tio.server.ServerGroupContext;
import org.tio.server.intf.ServerAioHandler;
import org.tio.server.intf.ServerAioListener;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

public class TioServer {
  //aioServer对象
  private final AioServer<Object, TioPacket, Object> aioServer;

  //有时候需要绑定ip，不需要则null
  private final String serverIp;

  //监听的端口
  private final int serverPort;

  public TioServer() {
    this(null, TioConstants.DEFAULT_PORT);
  }

  public TioServer(String serverIp, int port) {
    this.serverIp = serverIp;
    this.serverPort = port;
    //handler, 包括编码、解码、消息处理
    final ServerAioHandler<Object, TioPacket, Object> aioHandler = new TioServerAioHandler();
    //事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口
    final ServerAioListener<Object, TioPacket, Object> aioListener = null;
    //一组连接共用的上下文对象
    final ServerGroupContext<Object, TioPacket, Object> serverGroupContext = new
        ServerGroupContext<>(aioHandler, aioListener);
    aioServer = new AioServer<>(serverGroupContext);
  }

  @PostConstruct
  public void init() {
    try {
      aioServer.start(serverIp, serverPort);
      System.out.println("tio启动成功，端口：" + serverPort);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @PreDestroy
  public void dostory() {
    aioServer.stop();
  }
  /**
   * 启动程序入口
   */
//  public static void main(String[] args) throws IOException {
//    aioServer.start(serverIp, serverPort);
//  }
}